import csv
from datetime import datetime
from typing import List

from core.schedule_manager import ScheduleService
from models.schedule import Schedule


def export_schedules_to_csv(filepath: str, schedules: List[Schedule]) -> None:
    """将日程导出为 CSV 文件"""
    with open(filepath, mode='w', newline='', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        writer.writerow(["标题", "开始时间", "结束时间", "提醒时间", "备注"])
        for s in schedules:
            writer.writerow([
                s.title,
                s.start_time.strftime("%Y-%m-%d %H:%M") if s.start_time else "",
                s.end_time.strftime("%Y-%m-%d %H:%M") if s.end_time else "",
                s.reminder_at.strftime("%Y-%m-%d %H:%M") if s.reminder_at else "",
                s.notes or ""
            ])

def import_schedules_from_csv(filepath: str, user_id: int, db):
    """从 CSV 文件导入日程，绑定到指定用户"""
    with open(filepath, mode='r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        count = 0
        for row in reader:
            title = row.get("标题", "").strip()
            if not title:
                continue  # 跳过空标题

            def parse_time(val):
                val = val.strip()
                if not val:
                    return None
                try:
                    return datetime.strptime(val, "%Y-%m-%d %H:%M")
                except ValueError:
                    return None

            start_time = parse_time(row.get("开始时间", ""))
            if not start_time:
                continue  # 开始时间必填

            end_time = parse_time(row.get("结束时间", ""))
            reminder_at = parse_time(row.get("提醒时间", ""))
            notes = row.get("备注", "").strip()

            ScheduleService.add_schedule(
                db,
                user_id=user_id,
                title=title,
                start_time=start_time,
                end_time=end_time,
                reminder_at=reminder_at,
                notes=notes
            )
            count += 1
    return count